package functions

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/storage"
	"github.com/MzoroHaHa/dev-tools/backend/app/logger"
	"os"
)

var mainWindow fyne.Window

var functionsLogger = logger.NewLogger("functions")

func SelectDir() (string, error) {
	mainWindow.Resize(fyne.NewSize(800, 600))
	mainWindow.CenterOnScreen()

	ch := make(chan string)
	mainWindow.SetCloseIntercept(func() {
		mainWindow.Hide()
		ch <- ""
	})
	d := dialog.NewFolderOpen(func(reader fyne.ListableURI, err error) {
		mainWindow.Hide()
		if reader == nil || len(reader.Path()) == 0 {
			ch <- ""
			return
		}
		ch <- reader.Path()
	}, mainWindow)
	d.Resize(fyne.NewSize(800, 600))
	path, err := os.UserHomeDir()
	uri, err := storage.ParseURI("file://" + path)
	if err != nil {
		functionsLogger.Error("parse uri error", "error", err)
		return "", err

	}
	lUri, err := storage.ListerForURI(uri)
	if err != nil {
		functionsLogger.Error("lister uri error", "error", err)
		return "", err
	}
	d.SetLocation(lUri)
	mainWindow.Show()
	d.Show()
	targetPath := <-ch
	return targetPath, nil
}

func SelectFile() (string, error) {
	mainWindow.Resize(fyne.NewSize(800, 600))
	mainWindow.CenterOnScreen()

	ch := make(chan string)
	mainWindow.SetCloseIntercept(func() {
		mainWindow.Hide()
		ch <- ""
	})
	d := dialog.NewFileOpen(func(reader fyne.URIReadCloser, err error) {
		mainWindow.Hide()

		reader.URI().Path()
		if reader == nil || len(reader.URI().Path()) == 0 {
			ch <- ""
			return
		}
		ch <- reader.URI().Path()
	}, mainWindow)
	d.Resize(fyne.NewSize(800, 600))
	path, err := os.UserHomeDir()
	uri, err := storage.ParseURI("file://" + path)
	if err != nil {
		functionsLogger.Error("parse uri error", "error", err)
		return "", err

	}
	lUri, err := storage.ListerForURI(uri)
	if err != nil {
		functionsLogger.Error("lister uri error", "error", err)
		return "", err
	}
	d.SetLocation(lUri)
	mainWindow.Show()
	d.Show()
	targetPath := <-ch
	return targetPath, nil
}

func SetMainApp(app fyne.App) {
	mainWindow = app.NewWindow("dialog")
}
